package jlb.andriva.wrappers;

import android.os.AsyncTask;
import android.widget.LinearLayout;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import jlb.andriva.LoginActivity;

public class HttpTask extends AsyncTask<String, String, String> {
    @Override
    protected String doInBackground(String... uri) {
        HttpPost httppost = new HttpPost(uri[0]);
        String responseString = "";
        try {
            if(uri.length > 1){
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>((uri.length - 1) / 2);
                for(int i = 1; i< uri.length-1; i += 2){
                    nameValuePairs.add(new BasicNameValuePair(uri[i], uri[i+1]));
                }
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            }
            // Execute HTTP Post Request
            HttpResponse response = LoginActivity.webClient.execute(httppost);
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                responseString = out.toString();
                out.close();
            } else{
                //Closes the connection.
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }
        } catch (ClientProtocolException e) {
            return "ERROR: " + e.getMessage();
        } catch (IOException e) {
            return "ERROR: " + e.getMessage();
        }
        return responseString;
    }
    
    @Override
    protected void onCancelled() {
        
    }
}